package handler

import (
	"ginadmin/models"
	ctx "ginadmin/routes/context"
	"github.com/gin-gonic/gin"
)

type RoleHandler struct {
}

func (role *RoleHandler) Router(group *gin.RouterGroup) {
	group.GET("/role/list", role.List)
	group.POST("/role/add", role.Add)
	group.POST("/role/dels", role.Dels)
}
func (role *RoleHandler) Dels(c *gin.Context) {
	req := c.Request
	roles := req.FormValue("roles")
	if roles == "" {
		ctx.Err(c, 400, "删除菜单不能为空")
		return
	}
	r := &models.Role{}
	err := r.Dels(roles)
	if err != nil {
		ctx.Err(c, 400, err.Error())
		return
	}
	ctx.OK(c)
}
func (user *RoleHandler) Add(c *gin.Context) {
	req := c.Request
	name := req.FormValue("name")
	auth := req.FormValue("auth")

	if name == "" {
		ctx.Err(c, 400, "角色名称不能为空")
		return
	}

	//TODO 查找role name 如果有重复的。直接返回报错
	if models.FindRoleByName(name) {
		ctx.Err(c, 400, "此角色名称已存在")
		return
	}

	u := models.Role{Name: name, Auth: auth, Status: 1}
	u.Add()
	ctx.OK(c)
}

func (role *RoleHandler) List(c *gin.Context) {
	rolelist, err := models.RoleList()
	if err != nil {
		ctx.Map(c, ctx.M{"code": 401, "msg": err.Error(), "data": nil})
		return
	}
	ctx.Map(c, ctx.M{"code": 200, "msg": "OK", "data": rolelist})
}
